
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy

class gpImage():

    @staticmethod
    def add_text_with_transparent_box_to_file(image_path, text, output_path):
        # 打开图像
        image = Image.open(image_path).convert("RGBA")

        # 创建一个透明矩形框
        box_color = (0, 0, 0, 128)  # 透明度为一半（0-255，128 表示 50% 透明度）
        box_padding = 10
        font = ImageFont.load_default()

        # 自动换行文本
        max_width = image.width // 2
        lines = []
        line = ""
        for word in text.split():
            test_line = line + word + " "
            if font.getlength(test_line) <= max_width:
                line = test_line
            else:
                lines.append(line.rstrip())
                line = word + " "
        lines.append(line.rstrip())

        # 计算矩形框的高度
        line_height = font.getbbox("A")[3] - font.getbbox("A")[1]
        box_height = len(lines) * line_height + 2 * box_padding

        # 计算矩形框的宽度
        box_width = max([font.getlength(line) for line in lines]) + 2 * box_padding

        # 创建一个透明的图像来绘制矩形框和文本
        overlay = Image.new('RGBA', image.size, (0, 0, 0, 0))
        draw = ImageDraw.Draw(overlay)

        # 绘制矩形框
        draw.rectangle([(box_padding, box_padding), (box_width, box_height)], fill=box_color)

        # 在矩形框内绘制文本
        y = box_padding
        for line in lines:
            draw.text((box_padding * 2, y), line, fill=(255, 255, 255), font=font)
            y += line_height

        # 将透明图像与原始图像合并
        result = Image.alpha_composite(image, overlay)

        # 保存结果
        result.save(output_path)


    @staticmethod
    #rect = [(box_padding, box_padding), (box_width, box_height)]
    def add_text_with_transparent_box(image, text, rect):
        # 创建一个透明矩形框
        box_color = (0, 0, 0, 128)  # 透明度为一半（0-255，128 表示 50% 透明度）
        box_padding = 10
        font = ImageFont.load_default()

        # 自动换行文本
        max_width = rect[1][0] // 2
        lines = []
        line = ""
        for word in text.split():
            test_line = line + word + " "
            if font.getlength(test_line) <= max_width:
                line = test_line
            else:
                lines.append(line.rstrip())
                line = word + " "
        lines.append(line.rstrip())

        # 计算矩形框的高度
        line_height = font.getbbox("A")[3] - font.getbbox("A")[1]
        char_width = font.getbbox("A")[2] - font.getbbox("A")[0]
        #box_height = len(lines) * line_height + 2 * box_padding

        # 计算矩形框的宽度
        #box_width = max([font.getlength(line) for line in lines]) + 2 * box_padding

        # 创建一个透明的图像来绘制矩形框和文本
        overlay = Image.new('RGBA', image.size, (0, 0, 0, 0))
        draw = ImageDraw.Draw(overlay)

        # 绘制矩形框
        draw.rectangle([(rect[0][0], rect[0][1]), (rect[1][0], rect[1][1])], fill=box_color)

        # 在矩形框内绘制文本
        y = box_padding
        for line in lines:
            draw.text((box_padding * 2, y), line, fill=(255, 255, 255), font=font)
            y += line_height

        # 将透明图像与原始图像合并
        result = Image.alpha_composite(image, overlay)
        return result

    import numpy as np


    @staticmethod
    def putText2Cv2Frame(frame, text, rect):
        x = rect[0][0]
        y = rect[0][1]
        width= rect[1][0]
        height=rect[1][1]

        # 字体设置
        font = cv2.FONT_HERSHEY_SIMPLEX
        font_scale = 1
        color = (255, 255, 255)
        thickness = 2

        # 获取单个字符的宽度和高度
        (char_width, char_height), _ = cv2.getTextSize('A', font, font_scale, thickness)

        # 计算每行可容纳的最大字符数
        max_chars_per_line = width // char_width

        # 分割文本为多行
        lines = []
        while text:
            if len(text) <= max_chars_per_line:
                lines.append(text)
                text = ""
            else:
                # 找到最后一个空格作为换行点
                break_index = text[:max_chars_per_line].rfind(' ')
                if break_index == -1:
                    break_index = max_chars_per_line
                lines.append(text[:break_index])
                text = text[break_index:].lstrip()

        # 检查行数是否超过框的高度
        max_lines = height // (char_height + 5)  # 5 是行间距
        lines = lines[:max_lines]

        pt1 = (x,y)
        pt2 = (x+width, y+height)
        inverse_color = tuple(255 - c for c in color)
        cv2.rectangle(frame, pt1, pt2, inverse_color, thickness=-1)

        # 在框内逐行绘制文本
        for i, line in enumerate(lines):
            y_pos = y + (i + 1) * (char_height + 5)
            cv2.putText(frame, line, (x, y_pos), font, font_scale, color, thickness)

        return frame


    @staticmethod
    def test():
        # 使用示例
        image_path = "your_image.jpg"  # 替换为你的图像路径
        text = "This is a long text that needs to be wrapped inside the transparent box."
        output_path = "output_image.png"  # 替换为输出图像的路径
        add_text_with_transparent_box(image_path, text, output_path)